const Promise = require('bluebird');
const axios = require('axios');

const getQueryString = function (url, name) {
    var reg = new RegExp("[\?|\&]" + name + "=([^&]*)(&|$)", "i");
    var r = url.match(reg);
    if (r != null) return r[1];
    return null;
}

const getRealUrl = function (url) {
    return Promise.resolve().then(function () {
        if (url.indexOf('item.taobao.com/item.htm') != -1 || url.indexOf('detail.tmall.com/item.htm') != -1) {
            return url;
        }
        return axios.get(url).then(function (response) {
            let content = response.data;
            if (content.indexOf("var url = 'https://item.taobao.com/item.htm?") != -1) {
                let arr = content.match(/var url \= \'(https\:\/\/item\.taobao\.com\/item\.htm\?.*?)\';/i);
                if (arr && arr[1]) {
                    return arr[1];
                }
            } else if (content.indexOf("var url \= \'https\:\/\/a.m.taobao.com\/i") != -1) {
                let arr = content.match(/var url \= \'https\:\/\/a\.m\.taobao\.com\/i(.*?)\.htm\?.*?\';/i);
                if (arr && arr[1]) {
                    return 'https://item.taobao.com/item.htm?id=' + arr[1];
                }
            } else if (content.indexOf('"bizId":') != -1) {
                let arr = content.match(/"bizId"\s*:\s*"(\d*)"/i);
                if (arr && arr[1]) {
                    return 'https://detail.tmall.com/item.htm?id=' + arr[1];
                }
            }
            let url = response.request._redirectable && response.request._redirectable._isRedirect && response.request._redirectable._currentUrl;
            if (url.indexOf('item.taobao.com/item.htm') != -1 || url.indexOf('detail.tmall.com/item.htm') != -1) {
                return url;
            }
        });
    });
}


// getRealUrl('http://zmnxbc.com/s/IrkRi?tm=709f84').then(function(url){
//     console.log(url);
// });
let arr = '【樱优美抽屉式夹缝收纳柜厨房浴室缝隙柜储物柜塑料移动整理柜窄柜】，点击链接再选择浏览器打开http://c.b6wq.com/h.nEOchB?cv=sW8e0YfSC5v&sm=400b93 ，或复制这条信息￥sW8e0YfSC5v￥后打开👉手机淘宝👈'.match(/(http.*?)(，|\s|$)/i);
console.log(arr[1]);


getRealUrl('http://c.b6wq.com/h.nEOchB?cv=sW8e0YfSC5v&sm=400b93').then(function (url) {
    console.log(url);
    console.log(getQueryString(url, 'id'));
});
// getRealUrl('http://suo.im/2wx2Gc').then(function(url){
//     console.log(url);
// });